package com.tongtailian.www.stir.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.heiko.dropwidget.DropAdapter;
import com.heiko.dropwidget.DropBeanFlag;
import com.heiko.dropwidget.DropDownMenu;
import com.tongtailian.www.stir.R;
import com.tongtailian.www.stir.adapter.ConfigAdapter;
import com.tongtailian.www.stir.adapter.SelectCustomGroupAdapter;
import com.tongtailian.www.stir.adapter.SelectGroupAdapter;
import com.tongtailian.www.stir.base.BaseActivity;
import com.tongtailian.www.stir.bean.ConfigBean;
import com.tongtailian.www.stir.bean.ConfigDataFram;
import com.tongtailian.www.stir.bean.DeviceStateFram;
import com.tongtailian.www.stir.bean.NumberBean;
import com.tongtailian.www.stir.bleinterface.MyBleDeviceStateCallBack;
import com.tongtailian.www.stir.bleinterface.MyBleGattCallback;
import com.tongtailian.www.stir.utils.BleManageUtil;
import com.tongtailian.www.stir.utils.LogUtil;
import com.tongtailian.www.stir.utils.ProgressDlgUtil;
import com.tongtailian.www.stir.utils.ToastUtils;
import com.tongtailian.www.stir.utils.gson.GsonUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liuml on 2020/9/5 17:26
 */
public class SelectCustomParameActivity extends BaseActivity {
    private RecyclerView rvSampleNumber;



    private List<NumberBean> demoLocationList = new ArrayList<>();//研磨罐数量
    private List<ConfigBean> runTypelist = new ArrayList<>();//研磨模式
    private SelectCustomGroupAdapter selectCustomGroupAdapter;
    private ConfigAdapter configAdapter;

    private int oldSelectPosition = 0;
    String nameArray[] = {"根茎类", "叶菜类", "花果菜类", "干果类", "水果类", "谷物类", "鱼肉类", "其他类"};
    String valueArray[] = {"样品重量≤500克，如：萝卜、胡萝卜、豆薯、甘薯、主要有莴笋、茎用芥菜、球茎甘蓝、竹笋、土豆、莲藕、洋葱、大蒜等。",
            "样品重量≤500克，如：白菜、菠菜、苋菜、莴苣、韭菜、芹菜等",
            "样品重量≤500克，如：金针菜、花椰菜、紫菜薹、南瓜、黄瓜、冬瓜、丝瓜、番茄、辣椒、茄子、豆角等",
            "样品重量≤500克，如：杏仁、腰果、榛子、核桃、板栗、白果、花生、葵花子、南瓜子、板栗、杏仁等（坚果类需去壳）",
            "样品重量≤500克，如：草莓、蓝莓、覆盆子、橘子、柠檬、柚子、葡萄、桃、枣、龙眼、荔枝、苹果、梨、柿子等",
            "样品重量≤500克，如：薏米、高梁、大麦、糙米、红小豆、小米、黑豆、黄豆等",
            "样品重量≤500克，如：活鱼、虾、海鲜、牛肉、羊肉、猪肉。含内脏含熟食",
            "样品重量≤500克，难处理的样品：粉丝、西兰花、蒜苗等"};
    private String locationList;

    private List<DropBeanFlag> dropBeans = new ArrayList<>();;
    private MyBleDeviceStateCallBack myBleDeviceStateCallBack;
    private int flow;
    private int dataDev;
    private int doingIndex = -1;
    private BleManageUtil bleManageUtil;
    private Handler handler = new Handler();


    @Override
    public int setLayoutId() {
        return R.layout.activity_custom_select_parame;
    }

    @Override
    public void initVariables() {
        setTitle("选择参数");
        setTvRight("确认选择");
        llRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        llLeft.setVisibility(View.GONE);

        bleManageUtil = BleManageUtil.getInstance();//初始化蓝牙
        locationList = spManager.getLocationList();
        oldSelectPosition = spManager.getGroup();
        LogUtil.d("locationList = " + locationList);
        if (TextUtils.isEmpty(locationList)) {
            for (int i = 1; i <= 4; i++) {
                NumberBean bean = new NumberBean();
                bean.setName(String.valueOf(i) + "组");
                bean.setGroup_name("根茎类");
                bean.setConfig("根茎类："+"配置信息获取失败");
                bean.setGroup(0);
                bean.setSelect(true);
                demoLocationList.add(bean);
            }
            spManager.saveLocationList(GsonUtil.gsonString(demoLocationList));
        } else {
            demoLocationList = GsonUtil.jsonToList(locationList, NumberBean.class);
        }

        post_getconfigData(0);
    }

    public void  post_getconfigData(int posision){
        ProgressDlgUtil.showProgressDlg("读取中", this);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getconfigData(posision);
            }
        },300);
    }


    public void getconfigData(int posision){
        NumberBean numberBean = demoLocationList.get(posision);
        int group = numberBean.getGroup();
        BleManageUtil.getInstance().getConfigDataFrame(group, new MyBleGattCallback() {
            @Override
            public void onConfigSuccess(ConfigDataFram configDataFram) {
                super.onConfigSuccess(configDataFram);
                int time = configDataFram.getiTimeWork() / 10;
                int super_time = configDataFram.getiTimeSuper() / 10;
                int water_time = configDataFram.getiTimeWater() / 10;

                //叶菜类：时间5s/1000转/秒/渐进1次/浮动（未选中则不显示）/超声20秒1次/清水20秒0次/洗涤剂（未选中则不显示）/烘干（未选中则不显示）
                numberBean.setConfig(": 时间"+ time + "s; "  + configDataFram.getiMotorSpeed()
                        + "转/秒/渐进" + configDataFram.getcCountWork()+"次" +
                        configDataFram.getcClrModeHome()+
                        " /超声"+super_time+"秒"+configDataFram.getcCountSuper()+"次"+
                        " /清水"+water_time+"秒"+configDataFram.getcCountWater()+"次"
                        + configDataFram.getInClearHome() +
                        configDataFram.getcClrSelectHome());
                if(posision == 0){
                    post_getconfigData(1);
                }else if(posision == 1){
                    post_getconfigData(2);
                }else if(posision == 2){
                    post_getconfigData(3);
                }else if(posision == 3){
                    selectCustomGroupAdapter.notifyDataSetChanged();
                    ProgressDlgUtil.dismiss();
                }

            }

            @Override
            public void onConfigFail() {
                super.onConfigFail();
                numberBean.setConfig("：配置信息获取失败");
                if(posision == 0){
                    post_getconfigData(1);
                }else if(posision == 1){
                    post_getconfigData(2);
                }else if(posision == 2){
                    post_getconfigData(3);
                }else if(posision == 3){
                    selectCustomGroupAdapter.notifyDataSetChanged();
                    ProgressDlgUtil.dismiss();
                }
            }
        });
    }


    private void updateList(){
        String runType = spManager.getRunType();
        LogUtil.d("获取的runType = " + locationList);
        LogUtil.d("nameArray.length = "+nameArray.length);
        if (TextUtils.isEmpty(runType)) {
            for (int i = 1; i <= 63; i++) {
                ConfigBean bean = new ConfigBean();

                if (i <= nameArray.length) {
                    bean.setLook("查看");
                    bean.setEdit(false);
                    bean.setName(nameArray[i - 1]);
                    bean.setValue(valueArray[i - 1]);
                } else {
                    bean.setLook("编辑");
                    bean.setEdit(true);
                    bean.setName("自定义" + String.valueOf(i - 1));
                }
                bean.setSelect(false);
                runTypelist.add(bean);
            }
            LogUtil.d("保存的 = " + GsonUtil.gsonString(runTypelist));
            spManager.saveRunType(GsonUtil.gsonString(runTypelist));
        } else {
            runTypelist = GsonUtil.jsonToList(runType, ConfigBean.class);
            LogUtil.d("获取的的 = " + GsonUtil.gsonString(runTypelist));
        }
        dropBeans.addAll(runTypelist);
        //configAdapter.setNewData(runTypelist);
    }

    private void showPopListView(View tview, int currCheckedPos, int group_position) {
        if (dropBeans != null && dropBeans.size() > 0) {
            DropDownMenu.showCustom(getActivity(), dropBeans, 0.5F, tview, currCheckedPos, new DropAdapter.OnItemClickListener() {
                @Override
                public void onClick(View view, int position) {
                    //runTypelist.get(oldSelectPosition).setSelect(false);
                    //runTypelist.get(position).setSelect(true);
                    demoLocationList.get(group_position).setGroup(position);
                    demoLocationList.get(group_position).setGroup_name(runTypelist.get(position).getName());
                    //oldSelectPosition = position;
                    //spManager.saveRunType(GsonUtil.gsonString(runTypelist));
                    //spManager.saveSelectGroup(oldSelectPosition);
                    spManager.saveLocationList(GsonUtil.gsonString(demoLocationList));
                    String groupName = runTypelist.get(position).getName();

                    BleManageUtil.getInstance().getConfigDataFrame(position, new MyBleGattCallback() {
                        @Override
                        public void onConfigSuccess(ConfigDataFram configDataFram) {
                            super.onConfigSuccess(configDataFram);
                            int time = configDataFram.getiTimeWork() / 10;
                            int super_time = configDataFram.getiTimeSuper() / 10;
                            int water_time = configDataFram.getiTimeWater() / 10;

                            //叶菜类：时间5s/1000转/秒/渐进1次/浮动（未选中则不显示）/超声20秒1次/清水20秒0次/洗涤剂（未选中则不显示）/烘干（未选中则不显示）
                            ((Button)tview).setText(configDataFram.getcGroupName()
                                    + ": 时间"+ time + "s"  + configDataFram.getiMotorSpeed()
                                    + "转/秒/渐进" + configDataFram.getcCountWork()+"次" +
                                    configDataFram.getcClrModeHome()+
                                    " /超声"+super_time+"秒"+configDataFram.getcCountSuper()+"次"+
                                    " /清水"+water_time+"秒"+configDataFram.getcCountWater()+"次"
                                    + configDataFram.getInClearHome() +
                                    configDataFram.getcClrSelectHome());

                            demoLocationList.get(group_position).setConfig(": 时间"+ time + "s; "  + configDataFram.getiMotorSpeed()
                                    + "转/秒/渐进" + configDataFram.getcCountWork()+"次" +
                                    configDataFram.getcClrModeHome()+
                                    " /超声"+super_time+"秒"+configDataFram.getcCountSuper()+"次"+
                                    " /清水"+water_time+"秒"+configDataFram.getcCountWater()+"次"
                                    + configDataFram.getInClearHome() +
                                    configDataFram.getcClrSelectHome());

                        }

                        @Override
                        public void onConfigFail() {
                            super.onConfigFail();
                            ((Button)tview).setText(groupName+"：配置信息获取失败");

                        }
                    });
                }
            }, new DropDownMenu.OnDropDismissListener() {
                @Override
                public void onDismiss() {

                }
            });
        } else {
            ToastUtils.showCenter("数据为空");
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        updateList();
    }

    int enablePosition,nextEnablePosition;
    @Override
    public void initViews(Bundle savedInstanceState) {

        rvSampleNumber = findViewById(R.id.rv_sample_number);


        //研磨罐数量
        selectCustomGroupAdapter = new SelectCustomGroupAdapter(R.layout.adapter_item_custom_group, demoLocationList);

        rvSampleNumber.setLayoutManager(new LinearLayoutManager(this));
        rvSampleNumber.setAdapter(selectCustomGroupAdapter);

        selectCustomGroupAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                LogUtil.d("研磨模式点击" + position);
                switch (view.getId()) {
                    case R.id.bt_group_name:
                        LogUtil.d("研磨罐点击" + position);
                        int selCount = 0;
                        for (int i = 0; i < demoLocationList.size(); i++) {
                            if (demoLocationList.get(i).isSelect()) {
                                selCount++;
                            }
                        }
                        if(selCount == 0 && position == 0){
                            changeGroupType(position);
                        }else if(selCount > 0 &&(position+1 == selCount || position+1 == (selCount+1)) ){
                            changeGroupType(position);
                        }else{
                            ToastUtils.showCenter("请按顺序进行选择");
                        }
                        break;
                    case R.id.bt_config_name:
                        if (BleManageUtil.getInstance().isPlaying) {
                            ToastUtils.showCenter("设备运转中请先停止设备");
                            return;
                        }
                       showPopListView(view,demoLocationList.get(position).getGroup(),position);
                        break;
                }
            }
        });

    }

    public void changeGroupType(int position){

        if(doingIndex == position + 1){
            ToastUtils.showCenter("当前罐体研磨中");
            return;
        }

        if (demoLocationList.get(position).isSelect()) {
            demoLocationList.get(position).setSelect(false);
        } else {
            demoLocationList.get(position).setSelect(true);
        }
        selectCustomGroupAdapter.setNewData(demoLocationList);
        spManager.saveLocationList(GsonUtil.gsonString(demoLocationList));
    }

    private CountDownTimer timer;//定时器查询工作状态
    //这是定时器
    public void runDymCodeTimer() {
        LogUtil.d("runTimer启动定时器开始");
        if (timer != null) {
            LogUtil.d("启动定时器 失败 timer != null");
            return;
        }
        LogUtil.d("启动定时器 number = ");
        if (bleManageUtil != null && BleManageUtil.getInstance().isConnect) {
            LogUtil.d("启动定时器 number = ");
            timer = new CountDownTimer(Long.MAX_VALUE, 2000) {
                @Override
                public void onFinish() {
                    cancel();
                }

                @Override
                public void onTick(long millisUntilFinished) {
                    if (bleManageUtil != null && bleManageUtil.isPlaying && BleManageUtil.getInstance().isConnect) {
                        getDeviceState();
                        //getDevicemodle();
                    }
                }
            }.start();
        }
    }

    //这个方法可以在activity或者fragment销毁的时候调用，防止内存泄漏
    public void cancle() {
        if (timer != null) {
//            LogUtil.d("取消定时器");
            timer.cancel();
            timer = null;
        }
        if(handler != null){
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }


    /**
     * 获取设备状态
     */
    private void getDeviceState() {
        /**
         * Flow
         * 0x01 位置初始化
         * 0x02 定位流程
         * 0x03 超声波清洗
         * 0x04 热风烘干
         * 0x05 清水清洗
         * 0x06 研磨工作
         *
         * 正常流程结束，Flow = 0x06， Step = 0xA0.
         * 指令结束流程，Flow = 0x10， Step = 0xA0.
         * 异常结束流程，Flow = 0x10， Step = 0xA0.
         */
        if (myBleDeviceStateCallBack == null) {
            myBleDeviceStateCallBack = new MyBleDeviceStateCallBack() {

                @Override
                public void onDevicesState(DeviceStateFram deviceStateFram) {

                    //{name=1, Flow=6, Step=0, DataDev=0}
                    flow = deviceStateFram.getFlow();
                    int step = deviceStateFram.getStep();
                    LogUtil.d(" 当前设备状态 = " + GsonUtil.gsonString(deviceStateFram));


                    switch (flow) {

                        case 6:
                            LogUtil.d("研磨中 flow = 6  dataDev= " + dataDev + " getStep = " + deviceStateFram.getStep());
                            //0x06工 作流程 正在研磨
                            doingIndex = deviceStateFram.getDataDev();;
                            break;
                    }

                    if (step == 160) {
                        cancle();
                        doingIndex = -1;
                        /*for (int i = 0; i < demoLocationList.size(); i++) {
                            demoLocationList.get(i).setSelect(false);
                        }
                        selectCustomGroupAdapter.setNewData(demoLocationList);
                        spManager.saveLocationList(GsonUtil.gsonString(demoLocationList));
                        ToastUtils.showCenter("停止工作");*/

                    }
                }

                @Override
                public void onFail() {
                    //ToastUtils.showCenter("发送数据失败");

                }
            };
        }

        BleManageUtil.getInstance().readDevicesState(myBleDeviceStateCallBack);


    }

    @Override
    public void doBusiness() {
        spManager.saveCurModle(7);
        runDymCodeTimer();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancle();
    }
}